package com.zhulong.saas.cloud.gateway.webfilter;

import com.zhulong.saas.cloud.gateway.adapt.UserAdapt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 判断当前的租户，获取租户id存入到上线文中，便于后续的业务使用。
 */
@Component
@Order(Integer.MIN_VALUE)
@Slf4j
public class TenantWebFilter implements WebFilter {

    @Autowired
    private UserAdapt userAdapt;

    @Value("${default.tenant.id:1}")
    private Long defaultTenantId;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.debug(exchange.getRequest().getURI().getHost());
        String host = exchange.getRequest().getURI().getHost();
        Long tenantId = userAdapt.getTenantByHost(host, defaultTenantId);
        return chain.filter(exchange).subscriberContext(c -> c.put("tenantId", tenantId));
    }

}
